package ua.com.softway.mail;

import java.util.List;

import ua.com.softway.db.Persistence;
import ua.com.softway.db.Query;

/**
 * Storage for letters to be sent
 * Persist letters to DB for logging & restarting 
 */
class MailQueue {
    private final TransactionControl transactionControl = new TransactionControl();
    
    private final int batchSize;
    private final String[] messageStatesToSend;

    MailQueue(int batchSize, String[] messageStatesToSend) {
        this.batchSize = batchSize;
        this.messageStatesToSend = messageStatesToSend;
    }
    
    List<GeneratedMessage> take() throws InterruptedException {
        transactionControl.begin();

        Query<GeneratedMessage> q = new Query<GeneratedMessage>(GeneratedMessage.class, "state in (" + states() + ")", "priority desc, generated");
        q.setMaxResults(batchSize);
        
        List<GeneratedMessage> msg = q.getResultList();
        
        if (msg.isEmpty()) {
            transactionControl.commit();
            
            synchronized(this) {
                this.wait();
            }
        }
        
        return msg;
    }

    private String states() {
        StringBuilder s = new StringBuilder();
        
        for (String state : messageStatesToSend) {
            if (s.length() > 0) s.append(',');
            
            s.append('\'');
            s.append(state);
            s.append('\'');
        }
        
        return s.toString();
    }

    void offer(GeneratedMessage message) {
        Persistence.current().persist(message);
        
        NotifyMailerFilter.notifyMailer();
    }
}
